/*
本文件对TreadCach接口做封装,外部不用创建ThreadCach对象就能方便调用ThreadCach接口
*/

#pragma once
#include "Common.h"
#include "ThreadCach.h"
#include "PageCach.h"

static void* ConcurrentAlloc(size_t size) {
    if (size > MAXBYTES) {
        size_t align = SizeMapClass::RoundUp(size);//按页对齐
        size_t kpage = align / PAGE_SIZE;//计算需要多少页
        PageCach::GetInstance()->Lock();
        Span* span     =   PageCach::GetInstance()->NewSpan(kpage);
        span->isUse_   =   true;
        span->objSize_ =   align;//记录该span切分的内存块大小
        PageCach::GetInstance()->UnLock();
        return span->freelist_;
    }else {
        if (pTlsThreadCach == nullptr) {
            pTlsThreadCach = new ThreadCach;
        }
        return pTlsThreadCach->Allocate(size);
    }
}

static void ConcurrentFree(void* ptr) {
    Span* span = PageCach::GetInstance()->MapObjectToSpan(ptr);
    size_t size = span->objSize_;
    if (size > MAXBYTES) {
        PageCach::GetInstance()->Lock();
        PageCach::GetInstance()->ReleaseSpanToPageCach(span);
        PageCach::GetInstance()->UnLock();
    }else {
        pTlsThreadCach->DeAllocate(ptr, size);
    }
}
